import time

import requests
from bs4 import BeautifulSoup
from  datetime import  datetime


def get_cf_const():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
    }
    res = requests.get("https://codeforces.com/api/contest.list?gym=false", headers=headers)
    js = res.json()['result']
    # 把内容丢给 BeautifulSoup 解析
    l = []
    for j in js:
        if j["startTimeSeconds"] < time.time():
            break
        time1 = str(datetime.fromtimestamp(j["startTimeSeconds"]))
        name1 = j["name"]
        rt = j["durationSeconds"]
        lt ="0" + str(int(rt/3600)) + ":"
        sp = str(int((rt%3600)/60))
        if len(sp) == 1:
            sp = '0' + sp;
        lt+=sp
        lj = "https://codeforces.com/contests/" + str(j['id'])
        l.append([name1,time1,lj,lt])
    return l
def cmp(l):
    return l[0]
def list_to_string():
    l = get_cf_const()
    l.sort(key=cmp)
    cf=""
    for lt in l:
        cf += lt[0] + '\n开始时间 -> ' + lt[1][:len(lt[1])-3] + '\n比赛时长 -> ' + lt[3] +  '\n比赛地址 -> ' + lt[2] + '\n' + '\n'
    return cf
cf = list_to_string()
